package com.example.fashion.android.util.DBUtil;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by fashion on 2017/7/9.
 * 数据库帮助类
 */

public class DataBaseHelper extends SQLiteOpenHelper {
    //数据库Book表名
    public static final String TABLE_BOOK_NAME ="Book";
    //数据库Category表名
    public static final String TABLE_CATEGORY_NAME ="Category";

    //创建Book表的Sql语句
    public static final String CREATE_BOOK ="create table "+TABLE_BOOK_NAME+"(" +
            "id integer primary key autoincrement," +
            "author text," +
            "price real," +
            "pages integer," +
            "name text)";
    //创建Category表的Sql语句
    public static final String CREATE_CATEGORY="create table "+TABLE_CATEGORY_NAME+"(" +
            "id integer primary key autoincrement," +
            "category_name text," +
            "category_code integer)";

    //删除Book表的Sql语句
    public static final String DROP_BOOK="drop table if exists "+TABLE_BOOK_NAME;
    //删除Category表的Sql语句
    public static final String DROP_CATEGORY="drop table if exists "+TABLE_CATEGORY_NAME;

    private Context mContext;

    public DataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        this.mContext = context;
    }


    /**
     * 在这个类初始化的时候创建表,并且只会创建一次
     * @param sqLiteDatabase
     */
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_BOOK);
        sqLiteDatabase.execSQL(CREATE_CATEGORY);
    }

    /**
     * 更新数据库的方法(只需将数据库的版本号加1,再次执行这个方法的时候就会执行了)
     * @param sqLiteDatabase
     * @param oldVersion
     * @param newVersion
     */
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        sqLiteDatabase.execSQL(DROP_BOOK);
        sqLiteDatabase.execSQL(DROP_CATEGORY);
        onCreate(sqLiteDatabase);
    }
}
